#!/bin/bash
#Author: YangYi
#Date: 2024-11-27
#Version: v1
#Content VIP异常重启


# 检查是否传入了参数
if [ -z "$1" ]; then
   echo "Usage: $0 <query_path>"
   exit 1
fi
if [ -z "$2" ]; then
   echo "Usage: $0 <query_network>"
   exit 1
fi

# Keepalived路径,根据环境填写
search_dir=$1
network=$2


#集群VIP
VIPLIST=`ip -o -4 addr show | grep $network | grep -ivw "127.0.0.1\|lo" | awk '{print $4}' | awk -F "/" '{print $1}' | tail -n +2`

#挂载VIP的网卡
#SERVERINTERFACE=`ip -o -4 addr show | grep -v "127.0.0.1" | awk '{print $2}' | awk -F "/" '{print $1}' | grep -v lo | tail -n1`

#网关，可查看相关路由获取，并不一定都是.1主机是网关
SERVERGATEWAY=`ip route show default | awk '/default/ {print $3}'`


function keepalivedOP {
  
   # 读取VIPLIST变量并逐行处理
   while IFS= read -r vip; do

   # 跳过空行和注释行
   [[ -z "$vip" || "$vip" =~ ^# ]] && continue
 
   # 查找包含该IP地址的keepalived.conf文件
   keepalived_conf_path=$(find $search_dir -type f -name "keepalived.conf" -exec grep -lH -- "$vip" {} \; 2>/dev/null | cut -d: -f1 | head -n 1)
 
   # 如果找到了文件，提取其所在的keepalived目录路径
   if [[ -n "$keepalived_conf_path" ]]; then
      keepalived_dir=$(dirname "$keepalived_conf_path" | xargs -n 1 dirname)
 
      # 如果找到了keepalived目录，则进行ping测试
      if [[ -d "$keepalived_dir" ]]; then
         # 使用arping命令探测VIP5次
	 MASTER_ARP_REQUEST_COUNT=`/usr/sbin/arping -c 5 -I $network -s $vip $SERVERGATEWAY  |grep "Unicast reply from"| wc -l`
         echo "arping结果: " $MASTER_ARP_REQUEST_COUNT
 
         # 根据ping结果执行相应的操作
         #if [[ "$ping_result" == "FAILURE" ]]; then
         if [ $MASTER_ARP_REQUEST_COUNT -eq 0 ]; then
            stop_script="$keepalived_dir/bin/stop.sh"
            start_script="$keepalived_dir/bin/start.sh"

         # 检查stop.sh和start.sh脚本是否存在并具有执行权限
         if [[ -x "$stop_script" && -x "$start_script" ]]; then
            echo "VIP $vip is not reachable, stopping keepalived..."
            "$stop_script"
            sleep 1
            echo "Starting keepalived..."
            "$start_script"
         else
            echo "Warning: $stop_script or $start_script does not exist or is not executable!" >&2
         fi
      else
         echo "VIP $vip is reachable, skipping..."  >&2
      fi
    else
      echo "Warning: Could not determine keepalived directory for VIP $vip in file $keepalived_conf_path" >&2
    fi
  else
    echo "Warning: Could not find keepalived.conf for VIP $vip" >&2
  fi
  echo "$vip $keepalived_dir"
done <<< "$VIPLIST"   

}

keepalivedOP















